<?php

class Sistema_FornecedorController extends App_Controller_Action
{

    private $_table     = 'FORNECEDOR';
    private $_pk        = 'FOR_ID';
    private $_order_col = 'FOR_NOM';
    private $_order     = 'ASC';
    private $_sta_col   = 'FOR_STA';
    private $obj        = '';
    private $form       = '';
    //public  $db = '';
     
    public function init()
    {   
        //$this->db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $this->obj = new Sistema_Model_DbTable_Fornecedor();
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Sistema_Form_Fornecedor();
    }

    public function indexAction() {
        Zend_Loader::loadClass('tools','library');
        
        $where = $this->_pk . ' > 0';
       
        //$STA = $this->_getParam($this->_sta_col, 1);
        //$where .= ' and ' . $this->_sta_col . ' = ' . $STA;
        
        $dscfiltro = $this->_getParam('dscfiltro', '');
        
        if($dscfiltro > '') $where .= ' and FOR_NOM like "'. $dscfiltro . '%"';
        
        $this->view->dscfiltro = $dscfiltro;

        //$result = $this->obj->fetchAll($this->obj->select()->where($where)->order($this->_order_col.' '.$this->_order));
        $query = 'SELECT SQL_CACHE * FROM FORNECEDOR WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
    }
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_geral.js');
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_fornecedor.js?1=4');
        
        $this->view->form = $this->form;
        if($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if ($this->form->isValid($formData)) {
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    $data = $this->form->getValues();
                    
                    unset($data['SEG_IDS']);
                    
                    //print_r($formData);
                    //echo '<br><br>';
                    //print_r($formData['SEG_CAT']);
                    
                    if($id == 0){
                        $this->obj->insert($data);
                        $id =  $this->obj->getAdapter()->lastInsertId(); 
						
                        $fsc = new Sistema_Model_DbTable_FornecedorHasSetcat();
                        foreach($formData['SEG_CAT'] as $key => $arr_seg){
                            foreach($arr_seg as $seg){
                                $data_arr = array(
                                    'FOR_ID' => $id,
                                    'CTS_ID' => $key,
                                    'CAT_ID' => $seg,
                                );
                                $fsc->insert($data_arr);
                            }
                        }
                    }
                    else{
                        $this->obj->update($data, $this->_pk.' = ' . $id);
                        
                        $fsc = new Sistema_Model_DbTable_FornecedorHasSetcat();
                        $fsc->delete('FOR_ID = '.$id);
                        foreach($formData['SEG_CAT'] as $key => $arr_seg){
                            foreach($arr_seg as $seg){
                                $data_arr = array(
                                    'FOR_ID' => $id,
                                    'CTS_ID' => $key,
                                    'CAT_ID' => $seg,
                                );
                                $fsc->insert($data_arr);
                            }
                        }
                    }
                               
                    $this->_helper->redirector('index');
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.Errordb::descricaoError($ex->getCode()).'");</script>';
                echo $ex->getMessage();
                $this->form->populate($formData);
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->obj->fetchRow($this->_pk . ' = ' . $id)->toArray();
                $this->form->populate($data);
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {   
            //$data = array($this->_sta_col => 0);
            //$ok = (bool) $this->obj->update($data, $this->_pk . ' = ' . $id);
            $this->obj->delete($this->_pk . ' = ' . $id);
            
            $fsc = new Sistema_Model_DbTable_FornecedorHasSetcat();
            $fsc->delete($this->_pk . ' = ' . $id);
                        
            $mat = new Sistema_Model_DbTable_Material();
            $mat = $mat->fetchRow($this->_pk . ' = ' . $id);
            
            if(isset($mat->MAT_ID)){
                
                $fsc = new Sistema_Model_DbTable_MaterialHasCat();
                $fsc->delete('MAT_ID = ' . $mat->MAT_ID);
                
                $gradecor = new Sistema_Model_DbTable_GradecorHasCor();
                $cor = new Sistema_Model_DbTable_Cor();
                $cores = $cor->fetchAll('MAT_ID = ' . $mat->MAT_ID);
                foreach($cores as $cor) {
                    $gradecor->delete('COR_ID ='.$cor->COR_ID);
                }
                
                $mat->delete('MAT_ID = ' . $mat->MAT_ID);
                
                $cor->delete('MAT_ID = ' . $mat->MAT_ID);
            }
        }       
        //echo json_encode(array('ok' => $ok));
        $urlOptions = array('controller'=>$this->_controller,'action'=>'index');
        $this->_helper->redirector->gotoRoute($urlOptions);
    }
    
    public function categoriasAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $id = $this->_getParam('seg', 0);
        $arr_set = array();
        
        $links = '<link rel="stylesheet" type="text/css" href="'.$this->_urlbase.'/public/media/js/chosen/chosen.min.css" />';
        $links.= '<script type="text/javascript" src="'.$this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js"></script>';
        
        if ((int)$id > 0 ) {   
            
            $ok = true;
            
            $html = '<select id="SEG_CAT['.$id.'][]" name="SEG_CAT['.$id.'][]" class="chosen-select" multiple="multiple" style="width:500px;">';
            
            $obj = new Sistema_Model_DbTable_Categoria;
            //$row = $obj->fetchAll('CTS_ID ='.$id);
            $row = $obj->fetchAll($obj->select()->where('CTS_ID ='.$id)->order('CAT_NOM ASC'));
            
            $arr = array();
            foreach($row as $r){ //$arr[$r['MTL_ID']] = $r['MAT_NOM']; 
                $selected = array_search($r['CAT_ID'], $arr_set) > '' ? 'selected=""':'';            
                $html .= '<option '.$selected.' value="'.$r['CAT_ID'].'">'.$r['CAT_NOM'].'</option>'; 
            }
            $html .= '</select><br><br>'.$links.'<script>$(function(){ $(".chosen-select").chosen(); }); </script>';
            
        }       
        echo json_encode(array('ok' => $ok, 'html'=>$html));
    }
    
    
}